//
//  YSGNurseAppointmentMapViewModel.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2022/3/3.
//  Copyright © 2022 QDSG. All rights reserved.
//

import UIKit

class YSGNurseAppointmentMapViewModel: NSObject {
    
    //计算距离
    var distance : NSInteger?
    
    var tableData: Array<AMapTip>!

    var search: AMapSearchAPI!
    var currentRequest: AMapInputTipsSearchRequest?
    
    var completion: (() -> ())?
    var pushCompletion: ((_ distance : NSInteger) -> ())?
    
    override init() {
        super.init()
        tableData = Array()
        initSearch()
        
    }
    
    private func initSearch() {
        search = AMapSearchAPI()
        search.delegate = self
    }
    
    func searchTip(withKeyword keyword: String?)
    {
        print("keyword \(String(describing: keyword))")
        if keyword == nil || keyword! == "" {
            return
        }
        
        let request = AMapInputTipsSearchRequest()
        request.city = "温州";
        request.keywords = keyword
        
        currentRequest = request
        search.aMapInputTipsSearch(request)
    }
    
    func searchAMapDistanceSearch(_ destination :AMapGeoPoint)
    {
        let request = AMapDistanceSearchRequest()
        request.type = .walk
        request.origins = [destination]
        request.destination = AMapGeoPoint.location(withLatitude: 28.007848, longitude: 120.672047)
        search.aMapDistanceSearch(request)

    }
    
}


extension YSGNurseAppointmentMapViewModel: AMapSearchDelegate{
    func onDistanceSearchDone(_ request: AMapDistanceSearchRequest!, response: AMapDistanceSearchResponse!) {
        if response.results.count > 0 {
            distance = response.results.first?.distance
            pushCompletion?(distance ?? 0)
        }
    }
    
    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
//        let nsErr:NSError? = error as NSError
//        NSLog("Error:\(error) - \(ErrorInfoUtility.errorDescription(withCode: (nsErr?.code)!))")
    }
    
    func onInputTipsSearchDone(_ request: AMapInputTipsSearchRequest!, response: AMapInputTipsSearchResponse!) {
     
        if currentRequest == nil || currentRequest! != request {
            return
        }
        
        if response.count == 0 {
            return
        }
        
        tableData.removeAll()
        for aTip in response.tips {
            tableData.append(aTip)
        }
        if (completion != nil) {
            completion?()
        }
            
    }

}

